var $ = null;

jQuery(document).ready(function(){
   $ = jQuery;

    $playerP = $('.player-paging span');

   /*var data = {
		'action': 'my_action',
		'start': 0
	};

	// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
	$.post(ajaxurl, data, function(response) {
		console.log('Got this from the server: ' + response);
	});*/

   $playerP.on("click", function(e) {
   		var pageNumber = $(this).text();
   		getPage(e, pageNumber);
	});
});

function getPage(e, pageNumber) {
	var data = {
		'action': 'my_action',
		'start': (pageNumber - 1) * 20,
		'length': 20,
		'type': $(e.target).data('type')
	};
	
	lastPlayerTable = $(e.target).data('type');

	// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
	$.post(ajaxurl, data, function(response) {
		console.log(lastPlayerTable);
		output_table_html(response);
	}, 'json');
}

function output_table_html(response) {
	console.log(lastPlayerTable);
	var tableId = lastPlayerTable == 'empty' ? '#player-table-missing-info' : '#player-table-with-all-info';
		console.log(tableId);
		$(tableId+' tbody').empty();
		var tr_html = '<tr>'+
			   '<td><input type="text" name="players[##player_id##][player_name]" value=""></td>'+
			   '<td><input type="text" name="players[##player_id##][player_boot]" value=""></td>'+
			   '<td><input type="text" name="players[##player_id##][player_nation]" value=""></td>'+
			   '<td><input type="text" name="players[##player_id##][player_club]" value=""></td>'+
			   '<td><input type="text" name="players[##player_id##][player_position]" value=""></td>'+
			   '<td><input type="text" name="players[##player_id##][player_foot]" value=""></td>'+
			   '<td><textarea name="players[##player_id##][player_fClubs]"></textarea></td>'+
			'</tr>'; 
		for(var i in response) {
			result__ = $(tableId+' tbody').append(tr_html.replace(/##player_id##/g, response[i].id));

			$('tbody').find('[name="players['+response[i].id+'][player_name]"]').val(response[i].name);
			$('tbody').find('[name="players['+response[i].id+'][player_boot]"]').val(response[i].boot);
			$('tbody').find('[name="players['+response[i].id+'][player_nation]"]').val(response[i].nation);
			$('tbody').find('[name="players['+response[i].id+'][player_club]"]').val(response[i].club);
			$('tbody').find('[name="players['+response[i].id+'][player_position]"]').val(response[i].position);
			$('tbody').find('[name="players['+response[i].id+'][player_foot]"]').val(response[i].foot);
			$('tbody').find('[name="players['+response[i].id+'][player_fClubs]"]').val(response[i].fClubs);
		}
}

String.prototype.replaceArray = function(find, replace) {
  var replaceString = this;
  for (var i = 0; i < find.length; i++) {
    replaceString = replaceString.replace(find[i], replace[i]);
  }
  return replaceString;
};